# 为图片设置ROI 
# ROI Region of Interest 兴趣区域
# 极大程度的减小处理区域
# 在 lesson 01 代码的基础上对图片进行裁剪

# 导入所需包
from functools import reduce
import matplotlib.pyplot as plt
import matplotlib.image as mping
import numpy as np

# 传入图片
img = mping.imread('test2.jpg')


# 输出图片格式与大小
print('This image is: ', type(img), 'with dimensions: ', img.shape)

# 复制图像的宽高
y = img.shape[0]
x = img.shape[1]

# 复制颜色选择
region_select = np.copy(img)
# print(color_select)

# 定一个三角形的区域 
# 默认原点 (0, 0) 在左上角
left_bottom = [0, 700]
right_bottom = [900, 600]
apex = [600, 320]

# 拟合线 (y = Ax + B) 识别ROI的三边区域
# np.polyfit() 用来返回系数 A B
fit_left = np.polyfit((left_bottom[0], apex[0]), 
                        (left_bottom[1], apex[1]), 1)

fit_right = np.polyfit((right_bottom[0], apex[0]), 
                        (right_bottom[1], apex[1]), 1)

fit_bottom = np.polyfit((left_bottom[0], right_bottom[0]), 
                        (left_bottom[1], right_bottom[1]), 1)

# 找到线内的区域
XX, YY = np.meshgrid(np.arange(0, x), np.arange(0, y))
region_thresholds = (YY > (XX*fit_left[0] + fit_left[1])) & \
                    (YY > (XX*fit_right[0] + fit_right[1])) & \
                    (YY < (XX*fit_bottom[0] + fit_bottom[1]))

# 将 ROI 设置为红色
region_select[region_thresholds] = [255, 0, 0]

# 可视化
plt.imshow(region_select)
plt.show()
